package store.web.servlet;

import store.domain.Cart;
import store.domain.Item;
import store.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

// 添加商品到购物车
public class AddItemToCartServlet extends HttpServlet {

    private static final String CART_FROM = "/WEB-INF/jsp/cart/cart.jsp";

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String workingItemId = req.getParameter("workingItemId");

        HttpSession session = req.getSession();
        Cart cart = (Cart) session.getAttribute("cart");

        if(cart == null){
            cart = new Cart();
        }

        if (cart.containsItemId(workingItemId)) {
            // 如果购物车里面已经有该商品，数量增加
            cart.incrementQuantityByItemId(workingItemId);
        } else {
            CatalogService catalogService = new CatalogService();
            boolean isInStock = catalogService.isItemInStock(workingItemId);
            Item item = catalogService.getItem(workingItemId);
            cart.addItem(item, isInStock);
        }

        session.setAttribute("cart",cart);
        // 跳转到该界面下
        req.getRequestDispatcher(CART_FROM).forward(req,resp);
    }
}
